A new version of SQL Server is released every few years. This year was no different with the launch of SQL Server 2012 in March. It is important to migrate older, unsupported databases to a current version. I am going to examine 3 different techniques to upgrade the [PUBS] sample database from SQL Server 2000 to 2008 R2.
The first two techniques require the database files to be copied from the older server to the new one. Use the ALTER DATABASE command to kick off the users and set the database off-line. Then copy the files to the target server.
1 2 3 4 5 6 7 |
-- Kick off users, roll back current work ALTER DATABASE [WILDLIFE] SET SINGLE_USER WITH ROLLBACK IMMEDIATE; GO -- Set the database to off-line ALTER DATABASE [WILDLIFE] SET OFFLINE GO |
For simplicity sake, the MSSQL directory on the C drive will hold both the data and log files. The first technique uses the CREATE DATABASE command with the FOR ATTACH clause.
1 2 3 4 5 |
-- Create database - upgrades it CREATE DATABASE [PUBS] ON (FILENAME = 'C:\MSSQL\Data\pubs.mdf'), (FILENAME = 'C:\MSSQL\LOG\pubs.ldf') FOR ATTACH; |
The second technique uses the sp_attach_db command to add the database to the default instance.
1 2 3 4 |
-- Attach database - upgrades it EXEC sp_attach_db @dbname = N'PUBS', @filename1 = N'C:\MSSQL\Data\pubs.mdf', @filename2 = N'C:\MSSQL\LOG\pubs.ldf'; |
The third and last technique depends upon a backup from the SQL Server 2000 server. I am using the RESTORE FILELISTONLY to get details on the backup.
1 2 3 |
-- Get file list RESTORE FILELISTONLY FROM DISK = 'C:\MSSQL\BACKUP\pubs.bak'; |
The restore technique requires a blank database to exist.
1 2 3 4 5 6 7 8 9 10 11 12 13 |
-- Define empty db CREATE DATABASE [PUBS] ON PRIMARY ( NAME = 'PubsData', FILENAME = 'C:\MSSQL\DATA\pubs.mdf', SIZE = 5MB, FILEGROWTH = 5MB) LOG ON ( NAME = 'PubsLog', FILENAME = 'C:\MSSQL\LOG\pubs.ldf', SIZE = 2MB, FILEGROWTH = 2MB) GO |
The RESTORE DATABASE command will overwrite the empty database and upgrade the internal structures.
1 2 3 4 5 6 7 |
-- Restore from backup RESTORE DATABASE [PUBS] FROM DISK = N'C:\MSSQL\BACKUP\pubs.bak' WITH FILE = 1, MOVE N'pubs' TO N'C:\MSSQL\DATA\PUBS.mdf', MOVE N'pubs_log' TO N'C:\MSSQL\LOG\PUBS.ldf', NOUNLOAD, REPLACE, STATS = 10 GO |
With all techniques, make sure the capatibility level is set to SQL Server 2008 R2 (100). It will be at SQL Server 2000 (80) after upgrading the database.
The system databases should never be moved from an older server to a newer one. If you need objects such as jobs from msdb, script them out and install them on the target server by executing the script. In summary, keep up to date with server versions so that you are not left in the dust when support is discontinued with your software.